package com.item.controller;


import com.github.pagehelper.PageInfo;
import com.item.bean.RPage;
import com.item.bean.Result;

import com.item.domain.GoodsCategoryName;
import com.item.po.GoodsPo;
import com.item.service.GoodsListService;
import com.item.utils.QiNiuYunUtils;

import org.apache.catalina.core.ApplicationPart;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
public class GoodsListController {

    @Autowired
    GoodsListService goodsListService;

    @Autowired
    QiNiuYunUtils qiNiuYunUtils;

    @PostMapping(value = "/goodsList/{limit}/{page}")
    public RPage<GoodsPo> GoodsList(
            @PathVariable(value = "limit", required = false) int limit,
            @PathVariable(value = "page", required = false) int page,
            @RequestBody(required = false) GoodsPo goods) {
        List<GoodsPo> goodss = goodsListService.findAll(limit, page, goods);

        PageInfo<GoodsPo> pageInfo = new PageInfo<>(goodss);
        RPage<GoodsPo> rPage = new RPage<>();
        rPage.setList(pageInfo.getList());
        rPage.setPageNum(pageInfo.getPageNum());
        rPage.setTotal(pageInfo.getTotal());
        rPage.setPages(pageInfo.getPages());
        rPage.setPageSize(pageInfo.getPageSize());
        return rPage;
    }

    /**
     * 根据id查
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/goods/list/{id}")
    public Result goodsList(@PathVariable(value = "id") int id) {
        Result result = new Result();
        GoodsPo id1 = goodsListService.findId(id);
        if (id1 != null) {
            result.setFlag(true);
            result.setMessage("数据返回成功");
            result.setData(id1);
        }
        return result;
    }

    @PostMapping(value = "/goodsList/add")
    public Integer goodsListAdd(@RequestBody GoodsPo goods) {

        int i = goodsListService.add(goods);

        return i;
    }

    @PutMapping(value = "/goodsList/update")
    public Integer goodsListUpdate(@RequestBody GoodsPo goods) {

        int i = goodsListService.update(goods);
        return i;
    }

    @PutMapping(value = "/reqUpdateShelves")
    public Integer reqUpdateShelves(@RequestBody GoodsPo goods) {
        int i = goodsListService.reqUpdateShelves(goods);
        System.out.println(goods.getGoodsStart());
        return i;
    }

    @DeleteMapping(value = "/goodsList/{id}")
    public Integer goodsListDelete(@PathVariable(value = "id") int id) {

        int i = goodsListService.delete(id);
        return i;
    }

    @GetMapping(value = "/goods/category/list")
    public Result goodsCategoryNameList() {
        Result result = new Result();
        List<GoodsCategoryName> goodsCategoryNames = goodsListService.goodsCategoryNameList();
        if (goodsCategoryNames != null) {
            result.setFlag(true);
            result.setMessage("数据请求成功");
            result.setData(goodsCategoryNames);
        }

        return result;
    }

    @PostMapping(value = "/goods/category/add")
    public Result goodsCategoryAdd(@RequestBody GoodsCategoryName goodsNameCategory) {

        Result result = new Result();
        int i = goodsListService.goodsCategoryAdd(goodsNameCategory);
        if (i == 1) {
            result.setFlag(true);
            result.setMessage("新增成功");
            result.setData(i);
        }
        return result;
    }

    @PutMapping(value = "/goods/category/update")
    public Result goodsCategoryUpdate(@RequestBody GoodsCategoryName goodsCategoryName) {
        Result result = new Result();
        int i = goodsListService.goodsCategoryUpdate(goodsCategoryName);
        if (i == 1) {
            result.setFlag(true);
            result.setMessage("数据修改成功");
            result.setData(i);
        }
        return result;

    }

    @GetMapping(value = "/test/update")
    public int goodsTestUpdate() {
        return goodsListService.goodsTestUpdate();
    }


    /**
     * 文件上传
     */
    @RequestMapping("/uploadPictures") //uploadPictures 这里的接口
    public String uploadPictures(@RequestParam("files") MultipartFile[] files) {

        //System.out.println(files);
        System.out.println("进来了");
        String url = "";
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                try {

                    //System.out.println(files);
                    FileInputStream fileInputStream = (FileInputStream) files[i].getInputStream();

                    url = qiNiuYunUtils.uploadQiniuYun(fileInputStream);

                    //System.out.println(url);
                    //输出url上传后的,可以复制url到浏览器访问
                    //System.out.println("url=" + url);
                    try {
                        //延迟两秒让七牛云缓一下 2000 等于2秒 不能缓的时间太长,前端没有渲染到图片会报错
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("返回图片地址" + url);
        //上传图片成功
        return url;
    }

    /**
     * 视频文件上传
     */
    @RequestMapping("/video/uploadPictures") //uploadPictures 这里的接口
    public String uploadPicturesVideo(@RequestParam("files") MultipartFile[] files) {

        //System.out.println(files);

        String url = "";
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                try {

                    //System.out.println(files);
                    FileInputStream fileInputStream = (FileInputStream) files[i].getInputStream();
                    url = qiNiuYunUtils.uploadQiniuYun(fileInputStream);

                    //System.out.println(url);
                    //输出url上传后的,可以复制url到浏览器访问
                    //System.out.println("url=" + url);
                    try {
                        //延迟两秒让七牛云缓一下 2000 等于2秒 不能缓的时间太长,前端没有渲染到图片会报错
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("返回图片地址" + url);
        //上传图片成功
        return url;
    }

    //本地存储路径
    //F:\reactnavite\springboot_react__log\springboot_demo02\src\main\java\com\item\Images

    //线上视频路径
    //http://qubvse5qe.hn-bkt.clouddn.com/6.mp4
//    public static void main(String[] args) throws Exception {
//
//        String videoPath = "http://qubvse5qe.hn-bkt.clouddn.com/777.mp4";
//        String ffmpeg_path = "F:/reactnavite/springboot_react__log/springboot_demo02/src/main/java/com/item/images/aaa.jpg";
//        GoodsListController.fetchFrame(videoPath,ffmpeg_path);
//    }
    //实现网络视频截取第一帧效果
    public static void fetchFrame(String videofile, String framefile)
            throws Exception {
        long start = System.currentTimeMillis();
        File targetFile = new File(framefile);
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
            if ((i > 48) && (f.image != null)) {
                break;
            }
            i++;
        }
        //        IplImage img = f.image;
        int owidth = f.imageWidth;
        int oheight = f.imageHeight;
        // 对截取的帧进行等比例缩放
        int width = 300;
        int height = (int) (((double) width / owidth) * oheight);
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage fecthedImage = converter.getBufferedImage(f);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                0, 0, null);
        //图片的路径以及名称-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        ImageIO.write(bi, "jpg", targetFile);


        ff.stop();
        System.out.println(System.currentTimeMillis() - start);
    }


    /***
     * 截取第一帧
     */
//    public static void main(String[] args) throws Exception {
//        String fileInputStream = "http://qubvse5qe.hn-bkt.clouddn.com/6.mp4";
//        //GoodsListController.executeCodecs(fileInputStream,null,null);
//    }


    /**
     * 文件上传
     */
    @RequestMapping("/uploadPicturesAudio") //uploadPictures 这里的接口
    public String uploadPicturesAudio(@RequestParam("files") Object object) {


        return "String";

    }


}
